package org.inspiration.dudu.web.service.content.imp;

import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.common.constant.RedisConstant;
import org.inspiration.dudu.common.util.FileUtil;
import org.inspiration.dudu.common.util.RedisUtil;
import org.inspiration.dudu.content.model.dto.CommentDTO;
import org.inspiration.dudu.content.model.entity.CommentEntity;
import org.inspiration.dudu.content.model.vo.AnswerVO;
import org.inspiration.dudu.content.model.vo.CommentVO;
import org.inspiration.dudu.content.model.vo.QuestionVO;
import org.inspiration.dudu.content.service.AnswerService;
import org.inspiration.dudu.content.service.ArticleService;
import org.inspiration.dudu.content.service.CommentService;
import org.inspiration.dudu.content.service.QuestionService;
import org.inspiration.dudu.user.service.UserService;
import org.inspiration.dudu.web.service.content.CommentFacadeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
@RequiredArgsConstructor
public class CommentFacadeServiceImpl implements CommentFacadeService {

    private final UserService userService;
    @Value("${dudu.file.upload-path}")
    private String uploadPath;

    private final FileUtil fileUtil;
    private final CommentService commentService;
    private final ArticleService articleService;
    private final QuestionService questionService;
    private final AnswerService answerService;

    /**
     * 上传评论
     * 
     * @param commentDTO 评论数据传输对象
     * @return 生成的唯一标识符
     */
    @Override
    @Transactional
    public String uploadComment(CommentDTO commentDTO) {
        String uuid = UUID.randomUUID().toString();
        String filename = uuid + ".html";
        Path subPath = Paths.get("comments", filename);
        // 将评论内容存入文件
        fileUtil.upload(commentDTO.getContent(), subPath);
        // 将评论实体存入数据库
        String contentFilePath = Paths.get(uploadPath).resolve(subPath).toString();
        CommentEntity commentEntity = commentService.transToEntity(commentDTO, contentFilePath, uuid);
        commentService.createComment(commentEntity);
        // 增加对应内容的评论数量
        String contentId = commentDTO.getParentId();
        switch (commentDTO.getContentType()) {
            case "article" -> {
                articleService.increaseCommentCount(contentId);
            }
            case "question" -> {
                questionService.increaseCommentCount(contentId);
            }
            case "answer" -> {
                answerService.increaseCommentCount(contentId);
            }
            case "comment" -> {
                commentService.increaseCommentCount(contentId);
            }
        }
        // 修改被回复用户的未读回复数
        userService.increaseUnreadCommentCount(commentDTO.getRepliedUserId());

        return uuid;
    }

    /**
     * 根据父级ID按升序获取评论
     * 
     * @param parentId 父级ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 评论视图对象列表
     */
    @Override
    public List<CommentVO> getCommentsByParentIdOrderByASC(String parentId, Integer pageNum, Integer pageSize) {
        return commentService.getCommentsByParentIdOrderByASC(parentId, pageNum, pageSize);
    }

    /**
     * 根据父级ID按降序获取评论
     * 
     * @param parentId 父级ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 评论视图对象列表
     */
    @Override
    public List<CommentVO> getCommentsByParentIdOrderByDESC(String parentId, Integer pageNum, Integer pageSize) {
        return commentService.getCommentsByParentIdOrderByDESC(parentId, pageNum, pageSize);
    }



    /**
     * 将评论标记为已读

     */
    @Override
    public void markAsRead(CommentDTO commentDTO) {
        // 将该comment标为已读
        commentService.markAsRead(commentDTO);

        //减少被回复用户的未读数量
        userService.decreaseUnreadCommentCount(commentDTO.getRepliedUserId());
    }

    @Override
    public List<Map<String, Object>> getReceiveCommentsByUserIdOrderByDESC(Long userId, Integer pageNum, Integer pageSize) {
        List<Map<String, Object>> res = new ArrayList<>();
        List<CommentEntity> commentEntityList = commentService.getReceiveCommentsByUserIdOrderByDESC(userId, pageNum, pageSize);
        for (CommentEntity commentEntity : commentEntityList) {
            Map<String, Object> map = new HashMap<>();
            map.put("contentType", commentEntity.getContentType());
            map.put("comment", commentService.transToVO(commentEntity));
            switch (commentEntity.getContentType()) {
                case "article" -> {
                    map.put("content", articleService.transToSimpleVO(articleService.getArticleById(commentEntity.getParentId()))) ;
                }
                case "question" -> {
                    QuestionVO questionVO = questionService.getQuestionById(commentEntity.getParentId());
                    map.put("content", questionVO);
                }
                case "answer" -> {
                    AnswerVO answerVO = answerService.getAnswerById(commentEntity.getParentId());
                    QuestionVO questionVO = questionService.getQuestionById(answerVO.getParentId());
                    map.put("content", answerVO);
                    map.put("question", questionVO);
                }
                case "comment" -> {
                    map.put("content", commentService.transToVO(commentService.getCommentByContentId(commentEntity.getParentId())) );
                }
            }
            res.add(map);
        }
        return res;
    }
}
